<?php
namespace app\common\behavior;

use GatewayWorker\Lib\Gateway;
use app\common\model\ShortcutReplay;
use app\common\model\xilumarket\ChatSession;
use app\common\model\xilumarket\GroupChatRead;
use think\Hook;

class Websocket
{
    public function websocketBindGroup($args) {
        list($userId, $client_id) = $args;
        $chat = new \addons\xilumarket\chatprograms\library\Chat();
        $sessions = ChatSession::where([
            'send_user_id|receive_user_id|delivery_user_id' => $userId, 
            'delivery_user_id' => ['<>', 0],
            'deletetime'  => null,
        ])->select();
        foreach ($sessions as $session) {
            Gateway::joinGroup($client_id, 'session_'. $session->id);
        }
        return $chat->init_data($userId);
    }

    public function autoreplay($args) {
        list($message, $userId, $session) = $args;
        $isGroup = $session['delivery_user_id'] > 0;
        $userinfo = [];
        foreach(['delivery_user_id' => 'delivery', 'receive_user_id' => 'seller','send_user_id'=> 'buyer'] as $key => $role) {
            if($session[$key] == $userId || $session[$key] == 0){
                continue;
            }
            $userinfo[$session[$key]] =  $role;
        }
        foreach($userinfo as $uid => $role){
            $replays = ShortcutReplay::where(['user_id' => $uid,'user_role' => $role])->select();
            $keyMsg = auto_replay($message['content'], $replays, 'key', false);
            // $msg = [];
            // foreach($replays as $replay){
            //     $msg[$replay['key']] = $replay->toArray();
            // }
            // $words = array_column($replays->toArray(), 'key');
            // foreach($words as &$word){
            //     $word = '/'.$word.'/';
            // }
            // preg_replace_callback($words, function($maths) use (&$msg) {
            //     if(isset($msg[$maths[0]])) {
            //         $msg[$maths[0]]['math'] = true;
            //         return $maths[0];
            //     }
            // }, $message['content'], -1, $count);
            // foreach($msg as $keyMsg) {
                // if(isset($keyMsg['math']) && $keyMsg){
            if($isGroup){
                $new_msg = [
                    'session_id' => $session['id'],
                    'send_user_id' => $keyMsg['user_id'],
                    'content' => $keyMsg['content'],
                    'chat_type' => $keyMsg['chat_type'], //类型:1=文字,2=图片,3=商品（废弃）
                ];
                list($returnData) = Hook::listen('create_group_message', $new_msg);
                $returnData['type'] = 'say';
                Gateway::sendToGroup('session_'.$session['id'], json_encode($returnData));
            }else{
                $new_msg = [
                    'session_id' => $session['id'],
                    'send_user_id' => $keyMsg['user_id'],
                    'receive_user_id' => $userId,
                    'see_type' => 0,
                    'content' => $keyMsg['content'],
                    'chat_type' => $keyMsg['chat_type'], //类型:1=文字,2=图片,3=商品（废弃）
                ];
                list($returnData) = Hook::listen('create_personal_message', $new_msg);
                $returnData['type'] = 'say';
                Gateway::sendToUid('user_'. $userId, json_encode($returnData));
                Gateway::sendToUid('user_'. $keyMsg['user_id'], json_encode($returnData));
            }
            //     }
            // }
            return ['code' => 1, 'msg'=>'成功运行'];
        }
    }

    public function createChatInfo($args) {
        list($message, $userId, $session) = $args;
        $returnData = [];
        if($session['delivery_user_id']){      //如果是组
            $new_msg = [
                'session_id' => $session['id'],
                'send_user_id' => $userId,
                'content' => $message['content'],
                'chat_type' => $message['chat_type'], //类型:1=文字,2=图片,3=商品（废弃）
            ];
            list($returnData) = Hook::listen('create_group_message', $new_msg);
        }else{
            // 创建聊天数据
            $new_msg = [
                'session_id' => $session['id'],
                'send_user_id' => $userId,
                'receive_user_id' => $message['receive_user_id'],
                'see_type' => 0,
                'content' => $message['content'],
                'chat_type' => $message['chat_type'], //类型:1=文字,2=图片,3=商品（废弃）
            ];
            
            list($returnData) = Hook::listen('create_personal_message', $new_msg);
        }
        return $returnData;
    }
}